package com.ydzh.kfqgwvisitor.exception;

import cn.hutool.core.collection.CollectionUtil;
import com.ydzh.kfqgwvisitor.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
@Slf4j
public class CustomExceptionHandler {


    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result handle(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + "!";
        }
        return Result.buildError(errorMesssage);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result validationBodyException(MethodArgumentNotValidException exception) {
        List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
        List<String> errorMsg = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            errorMsg.add(allError.getDefaultMessage());
        }

        return Result.buildError(CollectionUtil.join(errorMsg, ","));

    }

    /* @ExceptionHandler(MethodArgumentNotValidException.class)
     @ResponseBody
     public Result exception(MethodArgumentNotValidException exception) {
         BindingResult result = exception.getBindingResult();
         final List<FieldError> fieldErrors = result.getFieldErrors();
         List<String> errorMsg = new ArrayList<>();

         for (FieldError error : fieldErrors) {
             errorMsg.add(error.getDefaultMessage());
         }
         return Result.buildError(CollectionUtil.join(errorMsg, ","));
     }*/

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handler(Exception e) {
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            log.error("[业务异常 {}] ", e);
            return Result.buildCodeAndMsg(baseException.getCode(), baseException.getMsg());
        } else {
            log.error("[系统务异常 {}]", e);
            return Result.buildError("全局异常，未知错误");
        }
    }


}
